/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.appconfig;


import java.io.IOException;

import org.apache.struts2.config.Result;
import org.jaxson.config.ApplicationConfiguration;
import org.jaxson.struts.BaseAction;
import org.jaxson.struts.reverseAjax.ReverseAjaxManager;


/**
 * Struts Action which recieves input from the application
 * configuration screen (displays the list of properties).
 * 
 * @author Joe Maisel
 */
@Result(name = "success", value = "/admin/configuration.jsp")
public class ApplicationConfigurationAction extends BaseAction
{
	private static final long serialVersionUID = 1748392745876984L;
	private Boolean overwrite = false;
	private String cmd = "";
	private String buffer;
	private String SESSION_KEY = ApplicationConfigurationAction.class.getName() + ".buffer";
	private static ApplicationConfiguration config;
	
	static{
		try
		{
			config = ApplicationConfiguration.getInstance();
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * @see org.jaxson.struts.BaseAction#handle()
	 */
	@Override
	public String handle()
	{
		if( session.getAttribute( SESSION_KEY ) == null || cmd.equals( "Reload Original" ) )
		{
			this.buffer = config.getContents();
			this.cmd = "Apply";
		}

		if( this.cmd.equals( "Apply" ) )
		{
			try
			{
				config.load( new StringBuffer( this.buffer ) );
				ApplicationConfiguration.getInstance().load( new StringBuffer( this.buffer ) );
				ApplicationConfigurationEvent evt = new ApplicationConfigurationEvent();
				ReverseAjaxManager.addToBatch( session, evt );
				ReverseAjaxManager.commitBatch( session );
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
			session.setAttribute( SESSION_KEY, this.buffer );
		}
		else
			this.buffer = session.getAttribute( SESSION_KEY ) + "";

		return "success";
	}

	/**
	 * Should the physical properties file be overwritten?
	 * 
	 * @return the overwrite
	 */
	public Boolean getOverwrite()
	{
		return overwrite;
	}

	/**
	 * @param overwrite
	 *            the overwrite to set
	 */
	public void setOverwrite( Boolean overwrite )
	{
		this.overwrite = overwrite;
	}

	/**
	 * Get the properties file as a String.
	 * 
	 * @return the buffer
	 */
	public String getBuffer()
	{
		return buffer;
	}

	/**
	 * @param buffer
	 *            the buffer to set
	 */
	public void setBuffer( String buffer )
	{
		this.buffer = buffer;
	}

	/**
	 * The command issues from the administration screen.
	 * 
	 * @return the cmd
	 */
	public String getCmd()
	{
		return cmd;
	}

	/**
	 * @param cmd
	 *            the cmd to set
	 */
	public void setCmd( String cmd )
	{
		this.cmd = cmd.trim();
	}
}
